/*
 * BanBu_TranslateViewController
 * @description 本文件提供对话中魔法工具箱中的多语言翻译的viewcontroller
 * @package
 * @author          ***
 * @copyright
 * @version 		1.0
 * @description 本文件提供对话中魔法工具箱中的多语言翻译的viewcontroller
 */

#import "BanBu_TranslateViewController.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "TKLoadingView.h"
#import "BanBu_AppDelegate.h"
#import "BanBu_NavButton.h"
#import "BanBu_ChatViewController.h"
#import "BanBu_ImageView.h"

@interface BanBu_TranslateViewController ()

@end

@implementation BanBu_TranslateViewController
-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    [super viewWillAppear:animated];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        // Custom initialization
    }
    return self;
}

-(void)dealloc
{
    [_activity release],_activity = nil;
    [_textLabel release],_textLabel = nil;
    [_inputView release],_inputView = nil;
    [_outputView release],_outputView = nil;
    [_languageContentView release],_languageContentView = nil;
    [_sourceLanguage release],_sourceLanguage = nil;
    [_targetLanguage release],_targetLanguage = nil;
    [_languageTitle release],_languageTitle = nil;
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setUpForDismissKeyboard];
    
    BanBu_ImageView * img1 = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable]autorelease];
    
    img1.frame = CGRectMake(0, 0, __MainScreen_Width, __MainScreen_Height);
    
    [self.view addSubview:img1];
    
    //发送按钮
    BanBu_NavButton *btn_send=[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    btn_send.position = ButtonPositionRight;
    btn_send.frame=CGRectMake(0, 0, 50, 30);
    [btn_send setTitle:NSLocalizedString(@"sendReply", nil) forState:UIControlStateNormal];
    [btn_send addTarget:self action:@selector(sendMsg) forControlEvents:UIControlEventTouchUpInside];
    btn_send.titleLabel.font = [UIFont systemFontOfSize:14];
    
    self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithCustomView:btn_send]autorelease];
    
    //文本输入框
    _inputView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300,85)];
    _inputView.textColor = [UIColor blackColor];
    self.inputView.font = [UIFont systemFontOfSize:18];
    _inputView.layer.borderColor = [[UIColor grayColor] CGColor];
    _inputView.layer.borderWidth = 1.0;
    _inputView.layer.cornerRadius = 4.0;
    _inputView.delegate = self;
    self.inputView.returnKeyType = UIReturnKeyDefault;
    self.inputView.keyboardType = UIKeyboardTypeDefault;
    [self.view addSubview:self.inputView];
    [_inputView release];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 300,25)];
    label.text = NSLocalizedString(@"TranslateWords", nil);
    label.textAlignment = UITextAlignmentLeft;
    label.numberOfLines = 1;
    label.textColor = [UIColor darkGrayColor];
    label.alpha = 0.6;
    _textLabel = label;
    [_inputView addSubview:_textLabel];
    [label release];
    
    UIButton *translateButton = [UIButton buttonWithType:UIButtonTypeCustom];
    translateButton.frame = CGRectMake(250, 110, 40, 40);
    [translateButton setBackgroundImage:[UIImage imageNamed:@"translate_button.png"] forState:UIControlStateNormal];
    [translateButton addTarget:self action:@selector(translateText) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:translateButton];
    
    _outputView = [[UITextView alloc] initWithFrame:CGRectMake(10, 165, 300,__MainScreen_Height-44-165-10)];
    _outputView.textColor = [UIColor blackColor];
    self.outputView.font = [UIFont systemFontOfSize:18];
    _outputView.layer.borderColor = [[UIColor grayColor] CGColor];
    _outputView.layer.borderWidth = 1.0;
    _outputView.layer.cornerRadius = 4.0;
    _outputView.editable = NO;
    self.outputView.returnKeyType = UIReturnKeyDefault;
    self.outputView.keyboardType = UIKeyboardTypeDefault;
    

    
    [self.view addSubview:self.outputView];
    [_outputView release];
    

    UIView * longPressView = [[UIView alloc]initWithFrame:CGRectMake(10, 165, _outputView.frame.size.width, _outputView.frame.size.height)];
    longPressView.backgroundColor = [UIColor clearColor];
    UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
    longPressView.userInteractionEnabled = YES;
    longPress.minimumPressDuration = 0.5f;
    [longPressView addGestureRecognizer:longPress];
    
    
    [self.view addSubview:longPressView];
    [longPressView release];
    [longPress release];
    
    UIActivityIndicatorView *acity = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
    acity.hidesWhenStopped = YES;
    acity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    acity.color = [UIColor darkGrayColor];
    acity.center = _outputView.center;
    _activity = acity;
    [self.view addSubview:acity];
    [acity release];
        
    //语言
    self.languageContentView = [[[UIView alloc]initWithFrame:CGRectMake(30, 110, 188, 50)] autorelease];
    self.languageContentView.backgroundColor = [UIColor clearColor];
    
    UIButton * chooseLanguage = [UIButton buttonWithType:UIButtonTypeCustom];
    [chooseLanguage setBackgroundImage:[UIImage imageNamed:@"languageType.png"] forState:UIControlStateNormal];
    [chooseLanguage setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    chooseLanguage.frame = CGRectMake(0, 0, 188, 40);
    [chooseLanguage addTarget:self action:@selector(chooseLanguage:) forControlEvents:UIControlEventTouchUpInside];
    chooseLanguage.tag = 1001;
    [chooseLanguage setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    
    laImageView = [[UIImageView alloc]initWithFrame:CGRectMake(155, 12, 16, 16)];
    laImageView.image = [UIImage imageNamed:@"trans_down.png"];
    [chooseLanguage addSubview:laImageView];
    [laImageView release];
    
    [self.languageContentView addSubview:chooseLanguage];
    [self.view addSubview:self.languageContentView];

    NSString *langauage=[MyAppDataManager getPreferredLanguage];
    if([langauage isEqual:@"zh-Hans"])
    {
        _languageType = 0;
    }
    else if([langauage isEqual:@"ja"])
    {
        _languageType = 7;
    }
    else if([langauage isEqual:@"ko"])
    {
        _languageType = 8;
    }
    else if([langauage isEqual:@"zh-Hant"])
    {
        _languageType = 0;
    }
    else
    {
        _languageType = 6;
    }

    
    self.sourceLanguage = [[UserDefaults valueForKey:@"transmitLanguage"] valueForKey:@"sourceLanguage"];
    self.targetLanguage = [[UserDefaults valueForKey:@"transmitLanguage"] valueForKey:@"targetLanguage"];
    self.languageTitle = [UserDefaults valueForKey:@"languageTitle"];
    _languageType = [[UserDefaults valueForKey:@"languageType"] integerValue];
    
    if (self.sourceLanguage == nil)
    {
        self.sourceLanguage = @"zh";
    }
    if (self.targetLanguage == nil)
    {
        self.targetLanguage = @"en";
    }
    if (self.languageTitle == nil)
    {
        self.languageTitle = @"中文->English";
    }

    [chooseLanguage setTitle:[NSString stringWithFormat:@"　%@",self.languageTitle] forState:UIControlStateNormal];
    

}

//发送按钮
-(void)sendMsg
{
    if(!_inputView.text.length)
    {
        _textLabel.hidden = YES;
        [_inputView  becomeFirstResponder];
    }
    else if(_inputView.text.length&&!_outputView.text.length)
    {
        [self translateText];
    }
    else //发送文本
    {
        //发送广播通知；
        NSDictionary * sendDic = [NSDictionary dictionaryWithObjectsAndKeys:_outputView.text,KeyContent,@"mg",KeyShowFrom,[NSNumber numberWithInt:ChatCellTypeText],KeyType, nil];
        [[NSNotificationCenter defaultCenter]postNotificationName:kSendMsgAllTypeNotification object:sendDic];
        [self popToChat];
    }
}

//旋转小箭头
-(void)rotateImageView
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    CGAffineTransform transform = CGAffineTransformRotate(laImageView.transform, -M_PI);
    laImageView.transform = transform;
    [UIView commitAnimations];
}


//选择语言
-(void)chooseLanguage:(UIButton *)button
{
    [_inputView resignFirstResponder];
    [self rotateImageView];
   
    [button bringSubviewToFront:self.languageContentView];
    
    BanBu_LanguageTypeViewController * languageType = [[BanBu_LanguageTypeViewController alloc]init];
    languageType.view.frame = CGRectMake(0, 20, __MainScreen_Width, __MainScreen_Height);
    languageType.selectedIndex = _languageType;
    languageType.delegate = self;
    [self presentViewController:languageType animated:YES completion:^{
        
    }];
}

-(void)textViewDidChange:(UITextView *)textView
{
    _textLabel.hidden = _inputView.text.length?YES:NO;
}

//翻译
-(void)translateText
{
    if(_inputView.text.length)
    {
        [_inputView resignFirstResponder];
        [_activity startAnimating];
        NSString * urlString =[NSString stringWithFormat:@"http://openapi.baidu.com/public/2.0/bmt/translate?client_id=cL7MKAop74XGk8kpiEK6wk0T&q=%@&from=%@&to=%@",[_inputView.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],self.sourceLanguage,self.targetLanguage];
        [AppComManager getTranslateUrl:urlString delegate:self];
    }
    else
    {
        [_inputView becomeFirstResponder];
        [_activity stopAnimating];
    }
}

-(void)popToChat
{
    [self.navigationController popToViewController:self.chat animated:YES];
}


-(void)longPress:(UILongPressGestureRecognizer *)longPress
{
    if(_inputView.text.length<=0)
    {
        [_inputView becomeFirstResponder];
        return;
    }
    if (longPress.state == UIGestureRecognizerStateBegan)
    {
        [self copyAction];
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:[NSString stringWithFormat:@"%@%@",NSLocalizedString(@"copyButton", nil),NSLocalizedString(@"finishButton", nil)]  activityAnimated:NO duration:1.2];
    }
}

-(void)copyAction
{
    //复制到粘贴板
    UIPasteboard *paste = [UIPasteboard generalPasteboard];
    
    paste.string = _outputView.text;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    [_activity stopAnimating];
    if (error)
    {
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:YES duration:1];
    }
    else
    {
        if([resDic valueForKey:@"trans_result"])
        {
            _outputView.text = [[[resDic valueForKey:@"trans_result"] objectAtIndex:0] valueForKey:@"dst"];
        }
    }
}

- (void)setUpForDismissKeyboard
{
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(tapAnywhereToDismissKeyboard:)];
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view addGestureRecognizer:singleTapGR];
                }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view removeGestureRecognizer:singleTapGR];
                }];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer
{
    [self.view endEditing:YES];
}

#pragma mark -
#pragma mark delegate

- (void)LanguageTypeView:(BanBu_LanguageTypeViewController *)LanguageTypeView didSelectIndex:(NSInteger)index
{
    if([self.view viewWithTag:100])
    {
        [[self.view viewWithTag:100]removeFromSuperview];
        [[self.view viewWithTag:101]removeFromSuperview];
    }
    
    //选择语言
    switch (index)
    {
        case 0:
        {
            self.sourceLanguage = @"zh";
            self.targetLanguage = @"en";
            self.languageTitle = @"中文->English";
            _languageType = 0;
        }
            break;
        case 1:
        {
            self.sourceLanguage = @"zh";
            self.targetLanguage = @"jp";
            self.languageTitle = @"中文->日本語";
            _languageType = 1;
        }
            break;
        case 2:
        {
            self.sourceLanguage = @"zh";
            self.targetLanguage = @"spa";
            self.languageTitle = @"中文->Española";
            _languageType = 2;
        }
            break;
        case 3:
        {
            self.sourceLanguage = @"zh";
            self.targetLanguage = @"kor";
            self.languageTitle = @"中文->한국어";
            _languageType = 3;
        }
            break;
        case 4:
        {
            self.sourceLanguage = @"en";
            self.targetLanguage = @"jp";
            self.languageTitle = @"English->日本語";
            _languageType = 4;
        }
            break;
        case 5:
        {
            self.sourceLanguage = @"jp";
            self.targetLanguage = @"en";
            self.languageTitle = @"日本語->English";
            _languageType = 5;
        }
            break;
        case 6:
        {
            self.sourceLanguage = @"en";
            self.targetLanguage = @"zh";
            self.languageTitle = @"English->中文";
            _languageType = 6;
        }
            break;
        case 7:
        {
            self.sourceLanguage = @"jp";
            self.targetLanguage = @"zh";
            self.languageTitle = @"日本語->中文";
            _languageType = 7;
        }
            break;
        case 8:
        {
            self.sourceLanguage = @"kor";
            self.targetLanguage = @"zh";
            self.languageTitle = @"한국어->中文";
            _languageType = 8;
        }
            break;
        case 9:
        {
            self.sourceLanguage = @"spa";
            self.targetLanguage = @"zh";
            self.languageTitle = @"Española->中文";
            _languageType = 9;
        }
            break;
            
        default:
        {
            self.sourceLanguage = @"zh";
            self.targetLanguage = @"en";
            self.languageTitle = @"";
            _languageType = 0;
        }
            break;
    }
    
    NSDictionary * languageTransmitDic = [NSDictionary dictionaryWithObjectsAndKeys:self.sourceLanguage,@"sourceLanguage",self.targetLanguage,@"targetLanguage", nil];
    
    //将选中的语言存起来
    [UserDefaults setValue:languageTransmitDic forKey:@"transmitLanguage"];
    [UserDefaults setValue:self.languageTitle forKey:@"languageTitle"];
    [UserDefaults setValue:[NSNumber numberWithInt:_languageType] forKey:@"languageType"];
    
    //更新按钮的显示
    UIButton * button = (UIButton *)[self.languageContentView viewWithTag:1001];
    [button setTitle:[NSString stringWithFormat:@"　%@",self.languageTitle] forState:UIControlStateNormal];
    
    [self rotateImageView];
    
    [LanguageTypeView dismissViewControllerAnimated:YES completion:^{
        
    }];
}


@end
